from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.http import HttpResponse
from Buyer.models import BuyerUser
import hashlib


def LoginValid(func):
    def inner(request, *args, **kwargs):
        cookie_id = request.COOKIES.get('id')
        cookie_phone = request.COOKIES.get('phone')
        session_id = request.session.get('id')
        if cookie_id and cookie_phone and session_id:
            return func(request, *args, **kwargs)
        else:
            return HttpResponseRedirect('/Buyer/login/')
    return inner


def setPassword(password):
    md5 = hashlib.md5()
    md5.update(password.encode())
    result = md5.hexdigest()
    return result


def base(request):
    return render(request, 'buyer/base.html', locals())


def register(request):
    error_message = ''
    if request.method == 'POST':
        phone = request.POST.get('phone')
        if phone:
            if phone.isdigit() and len(phone) == 11 and phone.startswith('1'):
                user = BuyerUser.objects.filter(telephone=phone).first()
                if not user:
                    password = request.POST.get('password')
                    password_to = request.POST.get('password_to')
                    if password == password_to:
                        new_user = BuyerUser()
                        new_user.telephone = phone
                        new_user.password = setPassword(password=password)
                        username = request.POST.get('username')
                        if not username:
                            new_user.username = '宝妈'
                        else:
                            new_user.username = username
                        new_user.save()
                        return HttpResponseRedirect('/Buyer/login/')
                    else:
                        error_message = '两次密码不一致'
                else:
                    error_message = '手机已经被注册，请直接登录'
            else:
                error_message = '手机号格式错误'
        else:
            error_message = '手机号不可以为空'
    return render(request, 'buyer/register.html', locals())


import time
import datetime
def login(request):
    error_message = ''
    if request.method == 'POST':
        phone = request.POST.get('phone')
        if phone:
            user = BuyerUser.objects.filter(telephone=phone).first()
            if user:
                password = request.POST.get('password')
                db_password = user.password
                if db_password == setPassword(password):
                    # 校验验证码
                    # 获取验证码
                    code = request.POST.get('valid_code')
                    # 由于filter获取到的是个数组，所以我们必须加索引[0]获取单个对象，否则下方会报错
                    codes = ValidCode.objects.filter(code_user=phone).order_by('-code_time')[0]
                    # 校验验证码是否存在，是否过期，是否被使用
                    now = time.mktime(datetime.datetime.now().timetuple())
                    db_time = time.mktime(codes.code_time.timetuple())
                    t = (now - db_time)/60
                    if codes and codes.code_state == 0 and t <= 5 and codes.code_content.upper() == code.upper():
                        response = HttpResponseRedirect('/Buyer/index/')
                        response.set_cookie('phone', user.telephone)
                        response.set_cookie('id', user.id)
                        request.session['id'] = user.id
                        return response
                    else:
                        error_message = '验证码错误'
                else:
                    error_message = '密码错误，请查证'
            else:
                error_message = '用户名不存在'
        else:
            error_message = '手机号不能为空'
    return render(request, 'buyer/login.html', locals())


def logout(request):
    url = request.META.get('HTTP_REFERER', 'Buyer/index/')
    response = HttpResponseRedirect(url)
    for k in request.COOKIES:
        response.delete_cookie(k)
    del request.session['id']
    return response


def index(request):
    return render(request, 'buyer/index.html', locals())


def personal_info(request):
    user_id = request.COOKIES.get('id')
    user = BuyerUser.objects.get(id=int(user_id))
    if request.method == 'POST':
        user.username = request.POST.get('username')
        user.age = request.POST.get('age')
        user.gender = request.POST.get('gender')
        user.email = request.POST.get('email')
        user.address = request.POST.get('address')
        user.photo = request.FILES.get('photo')
        user.save()
    return render(request, 'buyer/personal_info.html', locals())


import json
import requests
from MYSC.settings import DING_URL
def sendDing(content, to=None):
    headers = {
        'Content-Type': 'application/json',
        'Charset': 'utf-8'
    }
    requests_data = {
        'msgtype': 'text',
        'text': {
            'content': content
        },
        'at': {
            'atMobiles': [

            ],
            'isAtAll': True
        }
    }
    # 如果to有值（to是接收方）
    if to:
        # 就将to的值传入atMobiles的列表中
        requests_data['at']['atMobiles'].append(to)
        # 将是否发送给所有人设置为False
        requests_data['at']['isAtAll'] = False
    else:
        # 否则，清空列表
        requests_data['at']['atMobiles'].clear()
        # 将信息发送给所有人
        requests_data['at']['isAtAll'] = True
    sendData = json.dumps(requests_data)
    response = requests.post(url=DING_URL, headers=headers, data=sendData)
    # 将内容以json字符串的形式接收
    content = response.json()
    return content


import random
def random_code(len=6):
    """
    :param len: 验证码长度
    :return: 随机生成验证码
    """
    string = ''
    for i in range(0, 10):
        string += str(i)
    for i in range(97, 123):
        string += chr(i)
    for i in range(65, 91):
        string += chr(i)
    validCode = ''.join([random.choice(string) for i in range(len)])
    return validCode


from Buyer.models import ValidCode
from django.http import JsonResponse
def send_login_code(request):
    result = {
        'code': 200,
        'data': ''
    }
    if request.method == 'POST':
        telephone = request.POST.get('telephone')
        # 利用random_code函数随机生成验证码
        code = random_code(4)
        # 创建验证码实例对象
        c = ValidCode()
        # 由于我们创建验证码类模型时，时间是默认auto_now，状态默认是0(未使用)
        # 所以我们实际上只需要获取两个值就够了
        c.code_user = telephone
        c.code_content = code
        c.save()
        sendData = 'hello\n尊敬的用户：{}\n\t\t您的验证码是{}，为了你的信息安全，请不要告诉别人'.format(telephone, code)
        # 由于sendDing函数to有默认值None，所以只需要一个content参数就可以调用
        sendDing(sendData)
        result['data'] = '发送成功'
    else:
        result['code'] = 400
        result['data'] = '请求失败'
    return JsonResponse(result)
# Create your views here.
